package com.sxkf.template.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxkf.core.api.vo.R;
import com.sxkf.template.constants.CommonConstants;
import com.sxkf.template.constants.ViewTypeConstants;
import com.sxkf.template.entity.*;
import com.sxkf.template.service.*;
import org.jeecg.common.util.CheckEmptyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.jeecg.common.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
* (t_product)表控制层
*
* @author zgc
*/
@Api(tags="商品模块")
@RestController
@RequestMapping("/product")
public class ProductController {
    @Resource
    private ProductService productService;

    @Resource
    private ProductSpecService productSpecService;

    @Resource
    private ProductViewService productViewService;

    @Resource
    private UserService userService;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private CouponService couponService;


    @ApiOperation("新增商品")
    @PostMapping("/add")
    public R<Boolean> add(@RequestBody Product product){
        productService.add(product);
        return R.success();
    }

    @ApiOperation(value = "修改")
    @PostMapping(value = "/update")
    public R<?> update(@RequestBody Product product){
        productService.edit(product);
        return R.success();
    }

    @ApiOperation("分页查用户收藏商品")
    @GetMapping("/pageLike")
    public R<IPage<Product>> pageLike(@RequestParam Integer pageNo,
                                      @RequestParam Integer pageSize,
                                      @RequestParam String userId) {
        IPage<Product> page = productService.pageLike(pageNo, pageSize, userId);
        return R.success(page);
    }
    
    @ApiOperation("搜索商品")
    @GetMapping("/page")
    public R<IPage<Product>> page(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
                                  @RequestParam(required = false) String productName,
                                  @RequestParam(required = false,defaultValue = "1") @ApiParam("1=综合，2=销量，3=价格升序，4=价格降序") String sortType,
                                  @RequestParam(required = false) String userId) {
        return R.success(productService.page(productName, sortType,pageNo, pageSize,userId));
    }

    @ApiOperation("分类搜索")
    @GetMapping("/typePage")
    public R<IPage<Product>> typePage(@RequestParam Integer pageNo,
                                      @RequestParam Integer pageSize,
                                      @RequestParam(required = false) Double longitude,
                                      @RequestParam(required = false) Double latitude,
                                      @ApiParam("分类Id")
                                      @RequestParam(required = false) String cateId,
                                      @ApiParam("店铺类型 1=批发市场、2=线上店铺、3=实体店铺")
                                      @RequestParam(required = false) String storeType,
                                      @ApiParam("1=附近店铺、2=为你推荐、3=新店特惠")
                                      @RequestParam(required = false) String searchType){
        IPage<Product> page = productService.typePage(pageNo,pageSize,longitude,latitude,cateId,storeType,searchType);
        return R.success(page);
    }


    @ApiOperation("商品搜索历史记录")
    @GetMapping("/getHis")
    public R<List<String>> getHis(@RequestParam String userId){
        List<String> hisSearch = redisUtils.lGet(CommonConstants.HIS_SEARCH + ":" + userId, 0, -1);
        return R.success(hisSearch);
    }

    @ApiOperation("清空商品搜索历史记录")
    @GetMapping("/delHis")
    public R<?> delHis(@RequestParam String userId){
        redisUtils.del(CommonConstants.HIS_SEARCH + ":" + userId);
        return R.success();
    }


    @ApiOperation("查询店铺内商品")
    @GetMapping("/pageByStore")
    public R<IPage<Product>> pageByStore(@RequestParam Integer pageNo,
                                         @RequestParam Integer pageSize,
                                         @RequestParam(required = false) String userId,
                                         @RequestParam String storeId,
                                         @RequestParam(required = false) String productName,
                                         @RequestParam(required = false,defaultValue = "1")
                                             @ApiParam("1=综合/推荐，2=销量，3=价格升序，4=价格降序 5=新品")
                                             String sortType) {
        Page<Product> page = productService.page(new Page<>(pageNo,pageSize),new LambdaQueryWrapper<Product>()
                .eq(Product::getStoreId,storeId)
                .like(CheckEmptyUtil.isNotEmpty(productName),Product::getName,productName)
                .orderByDesc("2".equals(sortType),Product::getSaleCount)
                .orderByAsc("3".equals(sortType),Product::getLowestPrice)
                .orderByDesc("4".equals(sortType),Product::getLowestPrice)
                .orderByDesc("5".equals(sortType),Product::getCreateTime)
        );

        // 存缓存
        if (CheckEmptyUtil.isNotEmpty(productName) && CheckEmptyUtil.isNotEmpty(userId)) {
            List<String> hisSearch = redisUtils.lGet(CommonConstants.HIS_SEARCH + ":" + userId, 0, -1);
            if (hisSearch != null && !hisSearch.contains(productName)) {
                redisUtils.lSet(CommonConstants.HIS_SEARCH+":"+userId, productName);
            }
            // 搜索发现
            Double score = redisUtils.score(CommonConstants.SEARCH_FIND, productName);
            if (score != null) {
                redisUtils.incrementScore(CommonConstants.SEARCH_FIND,productName,1);
            }else {
                redisUtils.addZset(CommonConstants.SEARCH_FIND,productName,0);
            }
        }


        return R.success(page);
    }

    @ApiOperation(value = "天天特卖")
    @GetMapping(value = "/specialSale")
    public R<IPage<Product>> specialSale(@RequestParam Integer pageNo,
                                         @RequestParam Integer pageSize,
                                         @RequestParam(required = false)
                                             @ApiParam("传封顶价格，2.9封顶就传2.9")
                                             BigDecimal price,
                                         @ApiParam("店铺类型 1=批发市场、2=线上店铺、3=实体店铺")
                                         @RequestParam(required = false) String type){


        Page<Product> page = productService.specialSale(new Page<>(pageNo, pageSize),price,type);

//        Page<Product> page = productService.page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<Product>()
//                .le(!CheckEmptyUtil.isEmpty(price),Product::getLowestPrice, price));
        return R.success(page);
    }

    @ApiOperation(value = "排行榜分类详情")
    @GetMapping(value = "/rankDetail")
    public R<IPage<Product>> rankDetail(@RequestParam Integer pageNo,
                                        @RequestParam Integer pageSize,
                                        @RequestParam String categoryId){
        Page<Product> page = productService.page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<Product>()
                .eq(Product::getCategoryId, categoryId)
                .orderByDesc(Product::getSaleCount));
        return R.success(page);
    }

    @ApiOperation(value = "热搜商品")
    @GetMapping(value = "/hotSearch")
    public R<IPage<Product>> hotSearch(@RequestParam Integer pageNo,
                                       @RequestParam Integer pageSize){

        Page<Product> page = productService.page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<Product>()
                .eq(Product::getState,"1")
                .orderByDesc(Product::getSaleCount));

        return R.success(page);

    }


    @ApiOperation(value = "获取商品信息")
    @GetMapping(value = "/get")
    public R<Product> getProduct(@RequestParam String productId,
                                 @RequestParam(required = false) String userId){

        Product product = productService.getById(productId);
        if (CheckEmptyUtil.isEmpty(product)){
            return R.success(product);
        }
        List<ProductSpec> productSpecList = productSpecService.list(new LambdaQueryWrapper<ProductSpec>()
                .eq(ProductSpec::getProductId, productId));
        product.setProductSpec(productSpecList);

        productService.update(new LambdaUpdateWrapper<Product>()
                .setSql("search_count = search_count + 1")
                .eq(Product::getId, productId));


        // 加了个足迹
        if (CheckEmptyUtil.isNotEmpty(userId)){
            long count = productViewService.count(new LambdaQueryWrapper<ProductView>()
                    .eq(ProductView::getUserId, userId)
                    .eq(ProductView::getViewId, productId)
                    .eq(ProductView::getViewType, ViewTypeConstants.PRODUCT));
            if (count == 0){
                User user = userService.getById(userId);
                ProductView productView = new ProductView();
                productView.setViewId(productId);
                productView.setViewType(ViewTypeConstants.PRODUCT);
                productView.setUserId(userId);
                productView.setUserNickName(user.getNickName());
                productView.setUserAvatar(user.getAvatar());
                productViewService.save(productView);
            }

        }

        List<Coupon> couponList = couponService.list(new LambdaQueryWrapper<Coupon>()
                .eq(Coupon::getStoreId, product.getStoreId()));
        product.setCoupons(couponList);


        return R.success(product);
    }

    @ApiOperation(value = "根据id删除商品")
    @GetMapping(value = "/del")
    public R<String> delete(@RequestParam String productId){
        Boolean res = productService.delete(productId);
        if (res){
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }



}
